package main

import (
	"fmt"
	"io"
	"time"
)

func main() {
	// 创建一个同步的管道
	reader, writer := io.Pipe()

	// 使用一个 goroutine 向管道中写入数据
	go func() {
		defer writer.Close()
		time.Sleep(time.Second * 10)
		data := "Hello, this is data written to the pipe!"
		n, err := writer.Write([]byte(data))
		if err != nil {
			fmt.Println("Error writing data to pipe:", err)
			return
		}
		fmt.Printf("Wrote %d bytes to the pipe.\n", n)
	}()

	// 创建一个缓冲区
	buffer := make([]byte, 300)

	// 在主 goroutine 中从管道中读取数据
	n, err := io.ReadAtLeast(reader, buffer, 300)
	//n, err := reader.Read(buffer)
	if err != nil {
		fmt.Println("Error reading data from pipe:", err)
		return
	}
	fmt.Printf("Read %d bytes from the pipe: %s\n", n, buffer[:n])
}
